package com.chanjet.donkey.service.tree;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.chanjet.donkey.entity.Tree;
import com.chanjet.donkey.repository.TreeDao;

@Component
@Transactional
public class TreeService {
//	void insertBefore(Tree node, Tree to);
//	void insertAfter(Tree node, Tree to);
//	void prependTo(Tree node, Tree to);
	@Autowired
	private TreeDao treeDao;
	@PersistenceContext
	private EntityManager em;
	
	public void makeRoot(Tree node) {
		node.setLft(1L);
		node.setRgt(2L);
		node.setDepth(0);
		treeDao.save(node);
		node.setTree(node);
		node.setParent(node);
		treeDao.save(node);
	}
	
	public List<Tree> findSubtree(Tree node) {
		return treeDao.subtree(node.getId(), node.getLft(), node.getRgt());
	}
	
	public List<Tree> findRoots() {
		return treeDao.findRoots();
	}
	public void appendTo(Tree node, Tree to) {
		beforeInsert(node, to, to.getRgt(), 1);
		treeDao.save(node);
	}
	
	private void beforeInsert(Tree node, Tree to, long v, int depth) {
		System.out.println("node: [" + node.getId() + "] appendTo [" + to.getId() + "], v:" + v + ", depth: " + depth);
		node.setLft(v);
		node.setRgt(v + 1);
		node.setDepth(to.getDepth() + depth);
		node.setTree(to.getTree());
		node.setParent(to);
		
		treeDao.shiftLft(to.getTree().getId(), v,  2L);
		treeDao.shiftRgt(to.getTree().getId(), v, 2L);
//		shiftLeftRight(v, 2);
	}

}
